<?php

namespace beObject\MVC;

use beObject\Web\Template;
use beObject\MVC\Model;
use beObject\Primitive\String;

/**
 * This object is the view of the MVC.<br />
 * This class contains parsing methods.
 * @author Dany Mottier
 * @copyright MD Consult
 * @license http://www.gnu.org/licenses/gpl.html
 * @link http://www.beobject-framework.net/beobject/mvc/view/view-class/<br />
 * @package beObject\MVC
 * @version 3.0
 */
class View
    extends Template {

  /**
   * Parse the template with the model properties.<br />
   * In the template, keys for parsing are enclosed by '{' and '}' and keys for
   * translation are enclosed by '[' and ']'.
   * @param beObject\MVC\Model $model The model to work on.
   * @param beObject\Primitive\String $filename The template filename.
   * @link http://www.beobject-framework.net/beobject/mvc/view/view-__construct/
   */
  public function __construct(Model $model, String $filename) {
    parent::__construct($filename);

    if (!is_null($model)) {
      $this->parse($model);
    }
  }

  /**
   * Parse automatically each class property present in the template.<br />
   * The class property in the template must be enclosed by '{' and '}'.
   * @link http://www.beobject-framework.net/beobject/mvc/view/view-parse/
   */
  public function parse(Model $model) {
    $ignoredMethods = array("getMethods", "getVariables");
    $getters = get_class_methods(get_class($model));
    $counter = count($getters);

    for ($i = 0; $i < $counter; ++$i) {
      if (substr($getters[$i], 0, 3) == "get") {
        $classname = get_class($model);
        $myReflector = new \ReflectionMethod($classname, $getters[$i]);

        if (!in_array($getters[$i], $ignoredMethods)) {
          if ($myReflector->getNumberOfRequiredParameters() == 0) {
            $key = new String(substr($getters[$i], 3, strlen($getters[$i])));
            $value = new String(strval($model->{$getters[$i]}()));
            $this->setValue($key, $value);
          }
        }
      }
    }
  }

}

?>
